import { THEME_LIGHT, THEME_DARK, THEME_SYSTEM } from '../constants'
import { watch } from 'vue'
import store from '../store'

/*
 *@description: 初始化主题
 *@author: Mr.Tang
 *@date: 2023-12-14 22:25:27
 *@version: V1.0
 */
export default () => {
  watch(() => store.getters.themeType, changeTheme, {
    //初始化时执行一次
    immediate: true
  })
}

const changeTheme = (theme) => {
  let themeClassName = ''
  switch (theme) {
    case THEME_LIGHT:
      themeClassName = 'light'
      break
    case THEME_DARK:
      themeClassName = 'dark'
      break
    case THEME_SYSTEM:
      watchSystemThemeChange()
      themeClassName = matchMedia ? 'dark' : 'light'
      break
  }
  document.querySelector('html').className = themeClassName
}

/*
 *@description: 监听系统主题变更
 *@author: Mr.Tang
 *@date: 2023-12-14 23:18:02
 *@version: V1.0
 */
let matchMedia
const watchSystemThemeChange = () => {
  if (matchMedia) return
  matchMedia = window.matchMedia('(prefers-color-scheme:dark)')
  matchMedia.onchange = () => {
    changeTheme()
  }
}
